package cn.com.aiton.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    public static final Long JWT_TTL = 3600000L;
    public static final String JWT_KEY = "aiton";
    public static final String JWT_AUTH = "Authorization";
    public static final String JWT_ISSUER = "traffic_signal_controler_framework";
    /***
     * 创建令牌
     */
    public static String createToken(Long ttl , String id,String subject){

        if (ttl == null){
            ttl = JWT_TTL;
        }

        long expMillis = System.currentTimeMillis()+ttl;

        Date expDate = new Date(expMillis);

        JwtBuilder builder = Jwts.builder();
        builder.setId(id);
        builder.setIssuer(JWT_ISSUER);//颁发者
        builder.setIssuedAt(new Date());   //颁发时间
        builder.setExpiration(expDate);
        builder.setSubject(subject);
//      payload内部
//        Map<String,Object> map = new HashMap<>();
//        map.put("key","cccc");

//        builder.setClaims(map);
        builder.signWith(SignatureAlgorithm.HS256,JWT_KEY);   //签名算法，    密钥
        System.out.println(builder.compact());
        return builder.compact();
    }

    /**
     * 显示令牌
     * @param string
     */
    public static String parseJWT(String string){
        Claims claims =  Jwts.parser().
                setSigningKey(JWT_KEY).  //密钥
                parseClaimsJws(string).getBody();    //解析对象
        System.out.println(claims.toString());
        return claims.toString();
    }
}
